// 存放profile 相关的请求action
import { ApiResponse, User, UserProfile } from '@/types/data'
import { RootAction, RootThunkAction } from '@/types/store'
import http from '@/utils/request'
import { removeToken } from '@/utils/token'

// todo 用于创建获取个人信息的请求的action
export function userActionCreate(): RootThunkAction {
  return async (dispatch) => {
    const res = await http.get<ApiResponse<User>>('/user')
    console.log(res)

    dispatch({
      type: 'profile/set_user',
      payload: res.data.data,
    } as RootAction)
  }
}

// todo 发送请求获取个人详情页的数据存入reducer中
export function userProfileActionCreate(): RootThunkAction {
  return async (dispatch) => {
    const res = await http.get<ApiResponse<UserProfile>>('/user/profile')
    console.log('res', res)

    dispatch({
      type: 'profile/set_user_profile',
      payload: res.data.data,
    } as RootAction)
  }
}

// todo 更新个人信息的action
export function updateProfileActionCreate(
  data: Partial<UserProfile> // Partial 是所有的类型都变成可选的
): RootThunkAction {
  return async (dispatch) => {
    // 1. 发请求更新数据
    const res = await http.patch('/user/profile', data)
    console.log('res更新个人信息数据', res)

    // 发请求获取最新的数据存入producer
    await dispatch(userProfileActionCreate())
  }
}

// todo 更新头像的action
export function updataPhotoActionCreate(data: FormData): RootThunkAction {
  return async (dispatch) => {
    const res = await http.patch('/user/photo', data)
    console.log(' res', res)

    await dispatch(userProfileActionCreate())
  }
}

// todo 函数用于创建, 清除所有信息的action
export function logoutActionCreate(): RootThunkAction {
  return async (dispatch) => {
    // 确认退出 => 清除token (仓库, 本地), 清除用户资料(基本 详情), 返回登录页
    removeToken()

    dispatch({
      type: 'login/login',
      payload: {},
    } as RootAction)

    dispatch({
      type: 'profile/set_user',
      payload: {},
    } as RootAction)

    dispatch({
      type: 'profile/set_user_profile',
      payload: {},
    } as RootAction)
  }
}
